package com.simple.indiapay.service.impl;

import cn.hutool.core.net.URLEncoder;
import cn.hutool.crypto.digest.MD5;
import com.google.common.base.Joiner;
import com.google.common.escape.Escaper;
import com.google.common.hash.Hashing;
import com.google.common.net.UrlEscapers;
import com.google.gson.Gson;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @description:
 * @author: Mr.Kang
 * @create: 2021-11-06 02:01
 **/
public class BaseService {

    @Autowired
    Gson gson;

    /**
     * 签名
     *
     * @param map
     * @param secretKey
     * @return
     */
    public String md5(Map<String, Object> map, String secretKey, Set<String> ignoreNames) {
        String md5Str = buildMd5Str(map, secretKey, ignoreNames);
        String s = DigestUtils.md5Hex(md5Str).toUpperCase();
        return s;
    }


    /**
     * map排序后字符串
     *
     * @param params
     * @param secretKey
     * @return
     */
    public String buildMd5Str(Map<String, Object> params, String secretKey, Set<String> ignoreNames) {
        Escaper escaper = UrlEscapers.urlFormParameterEscaper();
        List<Map.Entry<String, Object>> collect = params.entrySet().stream().sorted(Comparator.comparing(Map.Entry::getKey))
                .filter(it -> {
                    if (ObjectUtils.isNotEmpty(ignoreNames)) {
                        return !ignoreNames.contains(it.getKey());
                    }
                    return true;
                })
                .filter(it -> {
                    Object value = it.getValue();
                    return StringUtils.isNotBlank(value + "");
                })
                .collect(Collectors.toList());
        String join = Joiner.on("&").withKeyValueSeparator("=").join(collect);
        return join + "&key=" + secretKey;
    }
}
